package com.imooc.controller;

import com.imooc.MinIOConfig;
import com.imooc.MinIOUtils;
import com.imooc.grace.result.GraceJSONResult;
import com.imooc.grace.result.ResponseStatusEnum;
import com.imooc.pojo.bo.Base64FileBO;
import com.imooc.utils.Base64ToFile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

/**
 * @version 1.0
 * @Author Mr.Yang
 * @Date 2024-08-27 15:47
 * @question: 文件控制层
 */

@RestController
@RequestMapping("file")
@Slf4j
public class FileController {

    //居家本地路径
//    public static final String host = "http://192.168.1.2:8000/";
    //公司本地路径
    public static final String host = "http://192.168.6.21:8000/";

    @GetMapping("hello")
    public Object hello() {
        return "Hello File Service~~~";
    }

    @Autowired
    private MinIOConfig minIOConfig;

    /**
     * 使用minIo上传文件
     *  更新用户头像
     * @param file
     * @param userId
     * @return
     * @throws Exception
     */
    @PostMapping("uploadFace")
    public GraceJSONResult uploadFace(@RequestParam("file") MultipartFile file, @RequestParam("userId") String userId) throws Exception {

        if (StringUtils.isBlank(userId)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }

        //获得文件原始名称
        String filename = file.getOriginalFilename();
        if (StringUtils.isBlank(filename)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
        }

        filename = "userFace/" + userId + "/" + filename;
        MinIOUtils.uploadFile(minIOConfig.getBucketName(), filename, file.getInputStream());

        String imageUrl = minIOConfig.getFileHost()
                + "/"
                + minIOConfig.getBucketName()
                + "/"
                + filename;
        return GraceJSONResult.ok(imageUrl);
    }

    /**
     * 更新 admin用户的头像
     *  管理端admin用户头像传来的是一个 Base64位的字符串 ,并不是一个MultipartFile文件
     *  这是长字符串 并不适合 ? 拼接
     * @param base64FileBO
     * @return
     * @throws Exception
     */
    @PostMapping("uploadAdminFace")
    public GraceJSONResult uploadAdminFace(@RequestBody @Valid Base64FileBO base64FileBO) throws Exception {

        String base64 = base64FileBO.getBase64File();

        String suffixName = ".png"; //后缀 推荐png占用空间较小
        String uuid = UUID.randomUUID().toString(); //文件名
        String objectName = "adminFace/" + uuid + suffixName;  //对象名

        //因为base64是无法直接上传到minIo 先在本地产生一个临时文件
        String rootPath = "E:/" + "MuPinWang" + File.separator;
        String filePath = rootPath
                + File.separator
                + "adminFace"
                + File.separator
                + objectName;

        //写入filePath文件
        Base64ToFile.Base64ToFile(base64, filePath);

        MinIOUtils.uploadFile(minIOConfig.getBucketName(), objectName, filePath);

        String imageUrl = minIOConfig.getFileHost()
                + "/"
                + minIOConfig.getBucketName()
                + "/"
                + objectName;

        //此处开启异步任务将保存在本地的图片进行删除
        CompletableFuture<GraceJSONResult> future  = CompletableFuture.supplyAsync(() -> {
            try {
                Files.deleteIfExists(Paths.get(filePath));
                log.info("File deleted successfully: {}", filePath);
                return GraceJSONResult.ok("File deleted successfully");
            } catch (IOException e) {
                log.error("Failed to delete file: {}", filePath);
                return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_DELETED_FAILD);
            }
        });

        GraceJSONResult graceJSONResult = future.join();
        if (!graceJSONResult.getSuccess()) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }
        return GraceJSONResult.ok(imageUrl);

    }

    /**
     * 上传公司logo
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("uploadLogo")
    public GraceJSONResult uploadLogo(@RequestParam("file") MultipartFile file) throws Exception {

        //获得文件原始名称
        String filename = file.getOriginalFilename();
        if (StringUtils.isBlank(filename)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
        }

        filename = "company/logo/" + filename;
        MinIOUtils.uploadFile(minIOConfig.getBucketName(), filename, file.getInputStream());

        String imageUrl = MinIOUtils.uploadFile(minIOConfig.getBucketName(),
                filename,
                file.getInputStream(),
                true);
        return GraceJSONResult.ok(imageUrl);
    }

    /**
     * 上传公司营业执照
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("uploadBizLicense")
    public GraceJSONResult uploadBizLicense(@RequestParam("file") MultipartFile file) throws Exception {

        // 获得文件原始名称
        String filename = file.getOriginalFilename();
        if (StringUtils.isBlank(filename)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
        }

        filename = "company/bizLicense/" + filename;
        String imageUrl = MinIOUtils.uploadFile(minIOConfig.getBucketName(),
                filename,
                file.getInputStream(),
                true);
        return GraceJSONResult.ok(imageUrl);
    }

    /**
     * 上传企业授权书
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("uploadAuthLetter")
    public GraceJSONResult uploadAuthLetter(@RequestParam("file") MultipartFile file) throws Exception {

        // 获得文件原始名称
        String filename = file.getOriginalFilename();
        if (StringUtils.isBlank(filename)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
        }

        filename = "company/AuthLetter/" + dealFilename(filename);
        String imageUrl = MinIOUtils.uploadFile(minIOConfig.getBucketName(),
                filename,
                file.getInputStream(),
                true);
        return GraceJSONResult.ok(imageUrl);
    }

    /**
     * uploadPhoto 批量上传企业相册
     * @param files
     * @param companyId
     * @return
     * @throws Exception
     */
    @PostMapping("uploadPhoto")
    public GraceJSONResult uploadPhoto(@RequestParam("files") MultipartFile[] files, String companyId) throws Exception {

        //如果企业id为null 就赋值 ""
        if (StringUtils.isBlank(companyId)) companyId = "";

        ArrayList<String> imageUrls = new ArrayList<>();
        for (MultipartFile file : files) {
            //获得文件原始名称
            String filename = file.getOriginalFilename();

            filename = "company/" + companyId + "/photo/" + dealFilename(filename);
            String imageUrl = MinIOUtils.uploadFile(minIOConfig.getBucketName(),
                    filename,
                    file.getInputStream(),
                    true);

            imageUrls.add(imageUrl);
        }

        return GraceJSONResult.ok(imageUrls);
    }

    private String dealFilename(String filename) {
        String suffixName = filename.substring(filename.lastIndexOf("."));
        String fName = filename.substring(0, filename.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString();
        return fName + "-" + uuid + suffixName;
    }

//    /**
//     * 使用SpringBoot实现文件上传
//     *  文件上传到本地
//     * @param file
//     * @param userId
//     * @param request
//     * @return
//     * @throws Exception
//     */
//    @PostMapping("uploadFace")
//    public GraceJSONResult uploadFace(@RequestParam("file") MultipartFile file, @RequestParam("userId") String userId, HttpServletRequest request) throws Exception {
//
//        //获取文件的原始名
//        String originalFilename = file.getOriginalFilename();
//
//        //原始名可能如 abc.123.def.png 这种 ,截取最后变得文件类型
//        if (StringUtils.isNotBlank(originalFilename)) {
//            String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
//
//            //用户头像的文件名直接使用 用户id+文件类型后缀
//            //如果 有查看历史头像的操作 则不允许这种操作 需要再加比如UUID等字符串拼接
//            String newFileName = userId + suffixName;
//
//            //设置文件的存储路径 比如存储到E盘
//            String rootPath = "E:/" + "MuPinWang" + File.separator;
//            //图片存储的完全路径
//            String filePath = rootPath + File.separator + "face" + File.separator + newFileName;
//
//            File newFile = new File(filePath);
//            if (!newFile.getParentFile().exists()) {
//                //文件路径不存在 则创建
//                newFile.getParentFile().mkdirs();
//            }
//            //将内存中的文件数据写入到磁盘
//            file.transferTo(newFile);
//
//            //生成web可以被访问的url地址
//            String userFaceUrl = host + "static/face/" + newFileName;
//
//            return GraceJSONResult.ok(userFaceUrl);
//        }
//
//        return GraceJSONResult.error();
//    }
//
//    /**
//     * 使用阿里云的oss上传文件
//     * @param file
//     * @param userId
//     * @return
//     * @throws Exception
//     */
//    @PostMapping("uploadFace")
//    public GraceJSONResult uploadFace(@RequestParam("file") MultipartFile file,
//                                       @RequestParam("userId") String userId) throws Exception {
//        //获得文件原始名称
//        String filename = file.getOriginalFilename();
//
//        filename = userId + File.separator + filename;
//        String imageUrl = OSSUtils.uploadFile(file, filename);
//
//        return GraceJSONResult.ok(imageUrl);
//    }


}

